package com.software.levelupandroid.home.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.ToggleButton;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.software.levelupandroid.R;
import com.software.levelupandroid.entity.Task;
import com.software.levelupandroid.entity.User;
import com.software.levelupandroid.home.ui.home.HomeViewModel;
import com.software.levelupandroid.taskIssue.view.activity.TaskIssueActivity;
import com.software.levelupandroid.utils.UserUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 待办Item的Adapter
 * @Author LiangYaJie
 * @CreateTime 2024年05月25日 17:57:58
 */
public class ToDoItemAdapter extends RecyclerView.Adapter<ToDoItemAdapter.ViewHolder> {

    private List<Task> tasks = new ArrayList<>();
    private Context context;
    private HomeViewModel homeViewModel;
    private static final int TYPE_TODO = 0;
    private static final int TYPE_TODO_DONE = 1;

    public ToDoItemAdapter(Context context, HomeViewModel homeViewModel) {
        this.context = context;
        this.homeViewModel = homeViewModel;
    }

    @Override
    public int getItemViewType(int position) {
        Task task = tasks.get(position);
        if (task.getTaskType() == 0 && task.getStatus() == 0){
            return TYPE_TODO;
        } else if (task.getTaskType() == 0 && task.getStatus() == 1) {
            return TYPE_TODO_DONE;
        }else {
            return 0;
        }
    }

    @NonNull
    @Override
    public ToDoItemAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = null;
        if (viewType == TYPE_TODO){
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_timeline_todo, parent, false);
        }else if (viewType == TYPE_TODO_DONE){
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_timeline_todo_done, parent, false);
        }
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ToDoItemAdapter.ViewHolder holder, int position) {
        Task task = tasks.get(position);
        holder.tbToDoFinish.setOnCheckedChangeListener(null);

        //最后一个任务的item不显示时间轴
//        if (position == tasks.size()-1) {
//            holder.vToDoTimeLine.setVisibility(View.INVISIBLE);
//        }else {
//            holder.vToDoTimeLine.setVisibility(View.VISIBLE);
//        }

        //设置创建时间
        holder.tvCreatedAt.setText(task.getCreatedAt());

        //设置任务完成状态
        holder.tbToDoFinish.setChecked(task.getStatus() == 1);

        //设置任务标题
        holder.tvToDoTaskTitle.setText(task.getTaskTitle());

        //设置任务类型
        if (task.getTaskType() == 0){
            holder.tvToDoTaskType.setText("待办");
        }

        //设置任务优先级
        switch (task.getPriority()){
            case 0:
                holder.tvToDoPriority.setText("不重要不紧急");
                break;
            case 1:
                holder.tvToDoPriority.setText("重要不紧急");
                break;
            case 2:
                holder.tvToDoPriority.setText("不重要紧急");
                break;
            case 3:
                holder.tvToDoPriority.setText("重要且紧急");
                break;
        }

        //恢复监听器
        holder.tbToDoFinish.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                User user = UserUtil.getUser(context);
                if (b){
                    task.setStatus(1);
                    user.setExperience(user.getExperience() + task.getExperience());
                    if(homeViewModel != null) homeViewModel.updateExperience(user.getExperience(), context);
                    UserUtil.saveUser(user, context);
                }else {
                    task.setStatus(0);
                    user.setExperience(user.getExperience() - task.getExperience());
                    if(homeViewModel != null) homeViewModel.updateExperience(user.getExperience(), context);
                    UserUtil.saveUser(user, context);
                }
                if (homeViewModel != null) homeViewModel.isFinishToDoTask(task, context);
                notifyItemChanged(holder.getAdapterPosition());
            }
        });

        //设置菜单按钮的点击监听器
        holder.ibToDoMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PopupMenu popup = new PopupMenu(view.getContext(), view);
                MenuInflater inflater = popup.getMenuInflater();
                inflater.inflate(R.menu.item_menu, popup.getMenu());
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem menuItem) {
                        switch (menuItem.getItemId()){
                            case R.id.item_edit:
                                Intent intent = new Intent(context, TaskIssueActivity.class);
                                intent.putExtra("task", task);
                                intent.putExtra("flag", 1);
                                context.startActivity(intent);
                                return true;
                            case R.id.item_delete:
                                if (homeViewModel != null && task.getTaskType() == 0)
                                    homeViewModel.deleteToDoTask(task, context);
                                notifyDataSetChanged();
                                return true;
                            default:
                                return false;
                        }
                    }
                });
                popup.show();
            }
        });

        //设置每个item的点击事件
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, TaskIssueActivity.class);
                intent.putExtra("task", task);
                intent.putExtra("flag", 1);
                context.startActivity(intent);
            }
        });

    }

    @Override
    public int getItemCount() {
        return tasks.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private TextView tvCreatedAt;
        private TextView tvToDoTaskTitle;
        private ImageButton ibToDoMore;
        private TextView tvToDoTaskType;
        private TextView tvToDoPriority;
        private ToggleButton tbToDoFinish;
        private View vToDoTimeLine;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvCreatedAt = itemView.findViewById(R.id.tv_todo_createdAt);
            tvToDoTaskTitle = itemView.findViewById(R.id.tv_todo_taskTitle);
            ibToDoMore = itemView.findViewById(R.id.ib_todo_more);
            tvToDoTaskType = itemView.findViewById(R.id.tv_todo_taskType);
            tvToDoPriority = itemView.findViewById(R.id.tv_todo_priority);
            tbToDoFinish = itemView.findViewById(R.id.tb_todo_finish);
            vToDoTimeLine = itemView.findViewById(R.id.v_todo_timeLine);
        }
    }

    /**
     * 更新任务列表
     * @param tasks
     */
    public void updateTaskList(List<Task> tasks){
        this.tasks.clear();
        this.tasks.addAll(tasks);
        notifyDataSetChanged();
    }

    /**
     * 任务列表新增
     * @param tasks
     */
    public void addTaskList(List<Task> tasks){
        this.tasks.addAll(tasks);
        notifyDataSetChanged();
    }
}
